package com.pocket.demo.core.mq.rabbitMQ.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * @author cookie. 【demo-MQ-rabbitMQ-3】
 *
 **/
//@Configuration
//@Import({DirectPublisher.class, DirectConsumer.class})
public class DirectExchangeConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(DirectConsumer.class);

    public static final String DIRECT_EXCHANGE = "pocket.direct";
    public static final String DIRECT_QUEUE_1 = "pocket.direct.queue_1";
    public static final String DIRECT_QUEUE_2 = "pocket.direct.queue_2";
    public static final String DIRECT_ROUTING_ERROR_KEY = "error";
    public static final String DIRECT_ROUTING_WARN_KEY = "warn";

    @Bean
    public MessageConverter messageConverter(){
        // 1.定义消息转换器
        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
        // 2.配置自动创建消息id，用于识别不同消息，也可以在业务中基于ID判断是否是重复消息
        jackson2JsonMessageConverter.setCreateMessageIds(true);
        return jackson2JsonMessageConverter;
    }

    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(DIRECT_EXCHANGE, true, false);
    }

    @Bean
    public Queue directQueue1(){
        return new Queue(DIRECT_QUEUE_1);
    }

    @Bean
    public Queue directQueue2(){
        return new Queue(DIRECT_QUEUE_2);
    }

    @Bean
    public Binding bindingQueue1(Queue directQueue1, DirectExchange directExchange){
        formatLog(directQueue1.getName(), directExchange.getName());
        return BindingBuilder.bind(directQueue1).to(directExchange).with(DIRECT_ROUTING_ERROR_KEY);
    }

    @Bean
    public Binding bindingQueue2(Queue directQueue2, DirectExchange directExchange){
        formatLog(directQueue2.getName(), directExchange.getName());
        return BindingBuilder.bind(directQueue2).to(directExchange).with(DIRECT_ROUTING_WARN_KEY);
    }

    private void formatLog(String queueName, String exchangeName){
        LOGGER.debug("RabbitMQ : 绑定队列【{}】到交换机【{}】", queueName, exchangeName);
    }

}
